﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using DataAnnotationsExtensions.Resources;

namespace DataAnnotationsExtensions
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class TwitterUserNameAttribute : DataTypeAttribute
    {
        //private static Regex _regex = new Regex(@"^[A-Z0-9]*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        public TwitterUserNameAttribute()
            : base(DataType.Text)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            if (ErrorMessage == null && ErrorMessageResourceName == null)
            {
                ErrorMessage = ValidatorResources.TwitterUserName_Invalid;
            }

            return base.FormatErrorMessage(name);
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            string valueAsString = value as string;
            return valueAsString != null && !IncludeTwitterDomainName(valueAsString);
        }

        private bool IncludeTwitterDomainName(string value)
        {
            string lowercase = value.ToLower();
            if (lowercase.StartsWith("http://twitter.com/") ||
                lowercase.StartsWith("http://www.twitter.com/") ||
                lowercase.StartsWith("twitter.com/") ||
                lowercase.StartsWith("www.twitter.com/") ||
                lowercase.StartsWith("https://twitter.com/") ||
                lowercase.StartsWith("https://www.twitter.com/"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
